package org.example.struct.array2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author liyishan
 * @date 2024/5/29 10:06
 * @apiNote
 */

public class Test02981MaximumLength {
    public static void main(String[] args) {
        String s = "abcaaba";
        System.out.println(maximumLength(s));
    }

    public static int maximumLength(String s) {
        int ans = -1;
        int len = s.length();
        List<List<Integer>> chs = new ArrayList<>(26);
        for (int i = 0; i < 26; i++) {
            chs.add(new ArrayList<>());
        }
        int cnt = 0;
        for (int i = 0; i < len; i++) {
            cnt++;
            if (i + 1 == len || s.charAt(i) != s.charAt(i + 1)) {
                int ch = s.charAt(i) - 'a';
                chs.get(ch).add(cnt);
                cnt = 0;
                for (int j = chs.get(ch).size() - 1; j > 0; j--) {
                    if (chs.get(ch).get(j) > chs.get(ch).get(j - 1)) {
                        Collections.swap(chs.get(ch), j, j - 1);
                    } else {
                        break;
                    }
                }
                if (chs.get(ch).size() > 3) {
                    chs.get(ch).remove(chs.get(ch).size() - 1);
                }
            }
        }
        for (int i = 0; i < 26; i++) {
            if (chs.get(i).size() > 0 && chs.get(i).get(0) > 2) {
                ans = Math.max(ans, chs.get(i).get(0) - 2);
            }
            if (chs.get(i).size() > 1 && chs.get(i).get(0) > 1) {
                ans = Math.max(ans, Math.min(chs.get(i).get(0) - 1, chs.get(i).get(1)));
            }
            if (chs.get(i).size() > 2) {
                ans = Math.max(ans, chs.get(i).get(2));
            }
        }
        return ans;
    }
}
